package com.share.common.utils;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import org.apache.commons.lang3.StringUtils;

public class GroovyUtil {
    final static String defaultMethodName = "parseJson";
    final static GroovyClassLoader groovyClassLoader = new GroovyClassLoader(GroovyUtil.class.getClassLoader());

    public static Object execute(String groovy) {
        return executeParam(groovy, defaultMethodName);
    }

    public static Object execute(GroovyObject groovyObject) {
        return executeParam(groovyObject, defaultMethodName);
    }

    public static Object execute(String groovy, String method) {
        return executeParam(groovy, method);
    }

    public static Object execute(GroovyObject groovyObject, String method) {
        return executeParam(groovyObject, method);
    }

    public static Object execute(String groovy, String method, String param) {
        return executeParam(groovy, method, param);
    }

    public static Object execute(GroovyObject groovyObject, String method, String param) {
        return executeParam(groovyObject, method, param);
    }

    /**
     * 创建一个  GroovyObject
     *
     * @param groovy
     * @return
     * @throws Exception
     */
    public static GroovyObject createGroovyObject(String groovy) throws Exception {
        Class aClass = groovyClassLoader.parseClass(groovy);
        GroovyObject groovyObject = (GroovyObject) aClass.newInstance();
        return groovyObject;
    }

    /**
     * 执行一个 GroovyObject对象通过groovy
     *
     * @param groovy
     * @param method
     * @param param
     * @return
     */
    private static Object executeParam(String groovy, String method, String... param) {
        Object reObject = null;
        if (StringUtils.isBlank(groovy) || StringUtils.isBlank(method)) {
            return null;
        }

        try {
            GroovyObject groovyObject = createGroovyObject(groovy);
            reObject = groovyObject.invokeMethod(method, param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return reObject;
    }

    //执行一个 GroovyObject对象通过groovy对象
    private static Object executeParam(GroovyObject groovyObject, String method, String... param) {
        Object reObject = null;
        if (groovyObject == null || StringUtils.isBlank(method)) {
            return null;
        }

        try {
            reObject = groovyObject.invokeMethod(method, param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return reObject;
    }
}
